import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt

# 生成模拟数据
# np.random.randint(1, 30, 100)
# 生成一个包含 100 个随机整数的数组，每个数都是从 1 到 29（包含 1 和 29）之间随机选取的
data = {
    'Recency': np.random.randint(1, 30, 100),  # 最近消费天数
    'Frequency': np.random.randint(1, 10, 100), # 消费次数
    'Monetary': np.random.randint(100, 1000, 100) # 消费金额
}
df = pd.DataFrame(data)
print(df.items)

# 数据标准化
scaler = StandardScaler()
X = scaler.fit_transform(df)

# 确定最佳K值（肘部法则）
sse = []
for k in range(1, 6):
    kmeans = KMeans(n_clusters=k, random_state=42)
    kmeans.fit(X)
    sse.append(kmeans.inertia_)

plt.plot(range(1,6), sse, marker='o')
plt.xlabel('Number of clusters (K)')
plt.ylabel('SSE')
plt.title('Elbow Method for Optimal K')
plt.show()

# 执行聚类（假设K=3）
kmeans = KMeans(n_clusters=3, random_state=42)
clusters = kmeans.fit_predict(X)

# 可视化聚类结果
df['Cluster'] = clusters
plt.figure(figsize=(10,6))
for i in range(3):
    plt.scatter(df[df['Cluster']==i]['Recency'], df[df['Cluster']==i]['Monetary'], label=f'Cluster {i}')
plt.xlabel('Recency')
plt.ylabel('Monetary')
plt.title('Customer Segmentation by RFM')
plt.legend()
plt.show()